package middle

import (
	"gf-mysql-transfer/internal/model"
	"github.com/gogf/gf/v2/net/ghttp"
	"net/http"
)

func MiddlewareHandlerResponse(r *ghttp.Request) {
	r.Middleware.Next()

	// There's custom buffer content, it then exits current handler.
	if r.Response.BufferLength() > 0 {
		return
	}
	var (
		msg         = "操作成功！"
		err         = r.GetError()
		res         = r.GetHandlerResponse()
		code        = http.StatusOK
		resultModel = model.BaseResponse{}
	)
	if err != nil {
		code = http.StatusInternalServerError
		msg = err.Error()
		resultModel.Type = "error"
	} else if r.Response.Status > 0 && r.Response.Status != http.StatusOK {
		msg = http.StatusText(r.Response.Status)
		switch r.Response.Status {
		case http.StatusNotFound:
			code = http.StatusNotFound
		case http.StatusForbidden:
			code = http.StatusNotFound
		}
	} else {
		resultModel.Type = "success"
	}
	resultModel.Code = code
	resultModel.Message = msg
	resultModel.Result = res
	r.Response.WriteJson(resultModel)

}
